package entity

import (
	"errors"
	"fmt"
	"strings"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//SpBmbgToEmps 部门变更_业绩转移员工
type SpBmbgToEmps struct {
	ID   int     `gorm:"column:ID;AUTO_INCREMENT;primary_key" json:"id"`
	SPID int     `gorm:"column:SPID" json:"spid"`
	YWLX int     `gorm:"column:YWLX" json:"ywlx"`
	EMID int     `gorm:"column:EMID" json:"emid"`
	DSVL float64 `gorm:"column:DSVL" json:"dsvl"`
	EMNO string  `gorm:"-" json:"emno"`
	EMNM string  `gorm:"-" json:"emnm"`
	DPNM string  `gorm:"-" json:"dpnm"`
}

//TableName SpBmbgToEmps表名
func (SpBmbgToEmps) TableName() string {
	return "T_SP_BMBG_TOEMPS"
}

//SpBmbgToEmpsEF 获取实体类对象
func SpBmbgToEmpsEF() base.EntityFunc {
	return func() interface{} {
		entity := SpBmbgToEmps{}
		return &entity
	}
}

//SpBmbgToEmpsESF 获取实体类对象数组
func SpBmbgToEmpsESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SpBmbgToEmps
		return &entities
	}
}

//BeforeSave 保存前的触发器
func (s *SpBmbgToEmps) BeforeSave(tx *gorm.DB) (err error) {
	emps := []SpBmbgToEmps{}
	err = tx.Where(`"SPID"=? and "YWLX"=?`, s.SPID, s.YWLX).Find(&emps).Error
	if err != nil {
		return
	}
	var EMNM string
	var DPNM string
	row := tx.Raw(`select "EMNM","DPNM" from "V_USER_DEPT" where "EMID"=?`, s.EMID).Row()
	row.Scan(&EMNM, &DPNM)
	if strings.Contains(DPNM, "离职") {
		return fmt.Errorf("不能将业绩分配离职人员！")
	}
	var LZEMID int
	var LZDPNM string
	tx.Table("T_SP_YGLZ").Where(`"FRID"=?`, s.SPID).Select(`"EMID"`).Row().Scan(&LZEMID)
	if LZEMID != 0 {
		sqlStr := `select "DPNM" from "V_USER_DEPT" where "EMID"=?`
		tx.Raw(sqlStr, LZEMID).Row().Scan(&LZDPNM)
		if DPNM != LZDPNM {
			return fmt.Errorf("不能将业绩分配给其他部门的员工！")
		}
	}
	total := 0.0
	for _, emp := range emps {
		total += emp.DSVL
		if emp.EMID == s.EMID {
			return errors.New("不能重复添加同一个员工！")
		}
	}
	total += s.DSVL
	if total-100 > 0.0001 {
		return errors.New("占比不能大于100%！")
	}
	return nil
}

func (s *SpBmbgToEmps) AfterFind(tx *gorm.DB) (err error) {
	sqlStr := `select "EMNO","EMNM","DPNM" from "V_USER_DEPT" where "EMID"=?`
	return tx.Raw(sqlStr, s.EMID).Row().Scan(&s.EMNO, &s.EMNM, &s.DPNM)
}
func init() {
	base.DaoPoolObj.Put("SpBmbgToEmps", base.NewDefaultDao(SpBmbgToEmpsEF(), SpBmbgToEmpsESF(), nil, "my"))
}
